package org.Lin.server;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import java.sql.Connection;
import java.sql.SQLException;

public class dbUtil {

    static Connection conn;

    static {
        try {
            Properties props = new Properties();
            props.load(dbUtil.class.getClassLoader().getResourceAsStream("config.properties"));

            String url = props.getProperty("DB_URL");
            String user = props.getProperty("DB_USER");
            String password = props.getProperty("DB_PASSWORD");

            conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static List<questionModel> getPendingQuestions() {
        List<questionModel> list = new ArrayList<>();
        String sql = "SELECT * FROM questions WHERE status = 'pending' AND model_used IS NULL";
        try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                list.add(new questionModel(rs.getInt("id"), rs.getString("question")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }


    public static void updateAnswer(int id, String answer, String model) {
        String sql = "UPDATE questions SET answer = ?, model_used = ?, status = 'answered' WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, answer);
            pstmt.setString(2, model);
            pstmt.setInt(3, id);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}